/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode[]} lists
 * @return {ListNode}
 */
var mergeKLists = function (lists) {
  if (lists.length == 0) {
    return []
  }
  if (lists.length == 1) {
    return lists[1]
  }
  let ptr1 = 0, ptr2 = 1
  while (ptr2 < lists.length) {
    lists[ptr2] = mergeList(lists[ptr1], lists[ptr2])
    ptr1++
    ptr2++
  }
  return lists[--ptr2]
}
function mergeList (l1, l2) {
  var l = new ListNode()
  var tail = l
  while (l1 && l2) {
    if (l1.val > l2.val) {
      tail.next = l2
      tail = tail.next
      l2 = l2.next
    } else {
      tail.next = l1
      tail = tail.next
      l1 = l1.next
    }
  }
  if (l1) {
    tail.next = l1
  }
  if (l2) {
    tail.next = l2
  }
  return l.next
}